package net.comm.common;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import magick.ImageInfo;
import magick.MagickException;
import magick.MagickImage;
import net.comm.pic.Jpicmk;
import net.comm.pic.Zoompic;
import net.comm.util.DatetimeUtil;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;

public class Fileload {
	
	static{
        //不能漏掉这个，不然jmagick.jar的路径找不到
        System.setProperty("jmagick.systemclassloader","no");
    }   
	
	static Logger logger = Logger.getLogger(Fileload.class.getName());
	
	//图片匹配字符串
	static private String picrex="\\S+(\\.jpg|\\.png|\\.bmp|\\.gif|\\.jpeg)";
	
	//水印字符串
	static final String WATER_STRING = ""; 	//
	
	private static int BUFFER_SIZE = 8096; //缓冲区大小		
	
	private String filepath;
	
	public Fileload(String path){
	
		filepath = path;		
	}
	
	public Fileload() {
		super();
		// TODO Auto-generated constructor stub
	}
	/*
	 * 保存网络文件到本地
	 */
	public void loadnet(String destUrl, String fileName, ReturnMessage msg) throws IOException  {
		
		try {		
			FileOutputStream fos = null;
			BufferedInputStream bis = null;
			HttpURLConnection httpUrl = null;
			URL url = null;
			byte[] buf = new byte[BUFFER_SIZE];
			int size = 0;
	
			//建立链接
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			//连接指定的资源
			httpUrl.connect();
			//获取网络输入流
			bis = new BufferedInputStream(httpUrl.getInputStream());
			
			//建立文件
			fos = new FileOutputStream( filepath + fileName); 
	
			//保存文件
			while ((size = bis.read(buf)) != -1){
				fos.write(buf, 0, size);
			}
			fos.close();
			bis.close();
			httpUrl.disconnect();
		} catch (Exception ex) {
			
			logger.error("上传文件出错" + filepath + fileName);
			return ;
		}	
	}

	// 删除文件处理
	public String delpic(FormFile file , ReturnMessage msg) {
		
		String filename = "";		
		return filename;
	}

		
	/*
	 * 新增文件处理
	 * upfile:待上传文件
	 * savefile:上传保存的文件名（不带路径）
	 * 
	 */
	public boolean  addfile(FormFile upfile, String savefile ) {

		String sfilepath= "";

		try {
			sfilepath = filepath + savefile;
			

			InputStream stream = upfile.getInputStream();// 读入待上传文件
			logger.debug(upfile.getFileName());
			
			OutputStream bos = new FileOutputStream(sfilepath);// 建立一个上传文件的输出流
			logger.debug(sfilepath);
			int bytesRead = 0;
			byte[] buffer = new byte[BUFFER_SIZE];
			while ((bytesRead = stream.read(buffer, 0, BUFFER_SIZE)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			stream.close();
		
			return true;
		} catch (Exception ex) {
			
			logger.error("上传文件出错" + sfilepath);
			return false;
		}
	}
	/*
	 * 新增图片处理
	 * upfile:待上传文件
	 * savefile:上传保存的文件名（不带路径）
	 * rarflag:是否需要压缩  rarflag=0 压缩  	rarflag=1：不压缩
	 * width:压缩后的宽度 height:压缩后的高度
	 * 
	 */
	public boolean  addfile(FormFile upfile, String savefile, int rarflag, int width, int height) {

		String sfilepath= "";

		try {
			sfilepath = filepath + savefile;
			
			boolean isPic = false;
			if(PatternMa.matchingText(picrex, savefile.toLowerCase())){
				isPic = true;
			}
			//对图片统一加水印
			if(isPic){
				if(width != 0 && height != 0) {//编辑过的图片才要先生成一个临时文件
					sfilepath = filepath + "T" + savefile;	
				}			
			}
			logger.debug(sfilepath);

			InputStream stream = upfile.getInputStream();// 读入待上传文件
			
			OutputStream bos = new FileOutputStream(sfilepath);// 建立一个上传文件的输出流
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			bos.close();
			stream.close();
		
			//对图片统一加水印
			if(isPic){
				/*
				//图片加水印 并自动压缩宽度到660
				Jpicmk.initTextToImg(sfilepath, filepath + savefile, WATER_STRING);		
			
				//需要生成压缩的小照片
				if(rarflag == 0){					
					Jpicmk.createThumbnail(filepath + savefile,	filepath+"zip"+savefile, width, height, 1);
				}				
		        File fF = new File(sfilepath);   
	       		if(fF != null){
	       			fF.delete();
	       		}*/	
				
				if(width != 0 && height != 0) {
					ImageInfo info = new ImageInfo(sfilepath);
					MagickImage image = new MagickImage(info);
	
					MagickImage toImage = image.scaleImage(width, height);// 缩放操作
					toImage.setFileName(filepath + savefile);// 设置输出的文件名
					toImage.writeImage(info); // 保存
					
					//删除临时的图片
					File fF = new File(sfilepath);   
		       		if(fF != null){
		       			fF.delete();
		       		}
				}
			}
			return true;
		} catch (Exception ex) {

			logger.error("上传文件出错" + sfilepath);
			return false;
		}
	}		
    /**  
     * 新建目录并返回该新建的目录  目录以日期分开
     * @param folderPath String 文件夹路径  
     * @return File 新建的目录  
     */  
     public String  newFolder (String webpath, String foldertype) throws Exception {   
         try {   
        	 //生成目录名
        	 String foldername =  GlbFinal.FILEPATH + foldertype + DatetimeUtil.getDate().substring(0,6);
        	 
     
        	 File folder = new File(webpath + foldername);   
             if (!folder.exists()) {   
                 folder.mkdirs();   
             }
             filepath = webpath + foldername + "\\";
             
        	 return foldername + "\\";  
          }catch (Exception e) {   
             e.printStackTrace();  
             logger.error("新建目录操作出错");
             throw new Exception ("新建目录操作出错");   
          }   
     }  
     /**  
      * 检查目录是否存在，不存在则创建 
      * @param folderPath String 文件夹路径  
      * @return File 新建的目录  
      */  
      public String  chkFolderExist (String webpath, String foldertype) throws Exception {   
          try {   
         	 //生成目录名
         	 String foldername =  foldertype ;
         	 
 			logger.debug(webpath + foldername);
     
         	 File folder = new File(webpath + foldername);   
              if (!folder.exists()) {   
                  folder.mkdirs();   
              }
              filepath = webpath + foldername ;
              
          	 return foldername ;  
           }catch (Exception e) {   
              e.printStackTrace();  
              logger.error("目录检查出错");
              throw new Exception ("目录检查出错");   
           }   
      }      
     /**  
      * 新建目录， 不按日期分目录，并返回该新建的目录  
      * @param folderPath String 文件夹路径  
      * @return File 新建的目录  
      */  
      public String  newFolderNodate (String webpath, String foldertype) throws Exception {   
          try {   
         	 //生成目录名
         	 String foldername =  GlbFinal.FILEPATH + foldertype ;
         	 
 			logger.debug(webpath + foldername);
     
         	 File folder = new File(webpath + foldername);   
              if (!folder.exists()) {   
                  folder.mkdirs();   
              }
              filepath = webpath + foldername + "\\";
              
          	 return foldername + "\\";  
           }catch (Exception e) {   
              e.printStackTrace();  
              logger.error("新建目录操作出错");
              throw new Exception ("新建目录操作出错");   
           }   
      }  
      
      public static void main(String[] args) throws MagickException {
    	  System.setProperty("jmagick.systemclassloader", "no");
    	  //中文路径有问题
    	  String sfilepath = "E:/project/iyoulin/03代码/web/userpic/grouppic/group0/T0762528104545.jpg";
    	  String sfilepath2 = "E:/project/iyoulin/03代码/web/userpic/grouppic/group0/T0762528104545_.jpg";
    	  ImageInfo info = new ImageInfo(sfilepath);
			MagickImage image = new MagickImage(info);

			MagickImage toImage = image.scaleImage(100, 100);// 缩放操作
			toImage.setFileName(sfilepath2);// 设置输出的文件名
			toImage.writeImage(info); // 保存
	}
	
}
